<script lang="ts" setup>
import { followCursor } from "tippy.js";
import { h, onMounted, ref, useSlots, type PropType } from "vue";
import { type TippyOptions, useTippy } from "vue-tippy";

defineOptions({
  name: "ReText",
});

const props = defineProps({
  lineClamp: {
    type: [String, Number],
  },
  tippyProps: {
    type: Object as PropType<TippyOptions>,
    default: () => ({}),
  },
});

const $slots = useSlots();
const textRef = ref();
const tippyFunc = ref();

const isTextEllipsis = (el: HTMLElement) => {
  if (!props.lineClamp) {
    return el.scrollWidth > el.clientWidth;
  } else {
    return el.scrollHeight > el.clientHeight;
  }
};

const getTippyProps = () => ({
  content: h(($slots.content as any) || $slots.default),
  // theme: "light", // 默认使用light主题
  // arrow: true, // 默认显示箭头
  // placement: "top", // 默认显示在上方
  // allowHTML: true, // 允许HTML内容
  // interactive: true, // 允许交互
  followCursor: true, // 跟随鼠标
  ...props.tippyProps,
});

function handleHover(event: MouseEvent) {
  if (isTextEllipsis(event.target as HTMLElement)) {
    tippyFunc.value.setProps(getTippyProps());
    tippyFunc.value.enable();
  } else {
    tippyFunc.value.disable();
  }
}

onMounted(() => {
  tippyFunc.value = useTippy(textRef.value?.$el, getTippyProps());
});
</script>

<template>
  <el-text v-bind="{
    truncated: !lineClamp,
    lineClamp,
    ...$attrs,
  }" ref="textRef" @mouseover.self="handleHover">
    <slot />
  </el-text>
</template>

<!-- :style="{
  display: lineClamp ? '-webkit-box' : 'block',
  '-webkit-box-orient': lineClamp ? 'vertical' : undefined,
  overflow: 'hidden',
  'text-overflow': !lineClamp ? 'ellipsis' : undefined,
  'white-space': !lineClamp ? 'nowrap' : undefined,
}" -->
